package com.qr.handler;

import com.qr.constant.Constant;
import com.qr.exception.BaseException;
import com.qr.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常，BaseException为一个父类，继承该父类的异常都会被捕获
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * sql异常处理
     * @param ex
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String msg = ex.getMessage();
        // 键值重复异常
        if (msg.contains("Duplicate entry")) {
            String[] split = msg.split(" ");
            String key = split[2];
            return Result.error(key +"已存在");
        } else {
            return Result.error("系统异常");
        }
    }

    // 文件大小超出限制异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<Result> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
        HttpStatus httpStatus = HttpStatus.REQUEST_ENTITY_TOO_LARGE; // HTTP状态码，这里是413
        return ResponseEntity.status(httpStatus).body(Result.error(Constant.UPLOAD_FILE_SIZE_LIMIT));
    }
}
